package com.jintu.portal.interceptor;

import com.jintu.portal.exception.RestException;
import com.jintu.portal.pojo.dto.TobUserDto;
import com.jintu.portal.pojo.entity.TInterLog;
import com.jintu.portal.utils.SessionUtil;
import com.jintu.portal.utils.StringUtil;
import com.jintu.portal.utils.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;

/**
 * 自定义拦截器
 */
@Component
public class MyInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(MyInterceptor.class);

    private String interStartTimeKey = "inter_start_time";

    private String CONTENT_TYPE = "application/json";

    @Value("${app_sign_key}")
    private String appSignKey;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.error("=========================================测试");
        String time = request.getParameter("time");
        String sign = request.getParameter("sign");
        if(StringUtil.isBlank(time, sign)) {
            throw new RestException("缺失公共参数");
        }
        request.setAttribute(interStartTimeKey, new Date());
        BufferedReader br = new BufferedReader(new InputStreamReader(SessionUtil.getRequest().getInputStream(), "utf-8"));
        String line = null;
        StringBuffer reqJson = new StringBuffer();
        while ((line = br.readLine()) != null) {
            reqJson.append(line);
        }
        br.close();
        String token = request.getParameter("token");
        if(StringUtil.isNotBlank(token)){
            request.setAttribute(UserUtil.USER_TOKEN_REQ_KEY, token);
        }
        if(!isOpenUrl(request) && StringUtil.isBlank(token)) {
            throw new RestException("缺失公共参数");
        }
        if(!isOpenUrl(request) && UserUtil.tobCurrentUser() == null) {
            throw new RestException(499, "用户token已失效");
        }
        //校验签名
        Long currentTime = Calendar.getInstance().getTimeInMillis() / 1000;
        Long intfTime = Long.parseLong(request.getParameter("time"));
        if(Math.abs(currentTime - intfTime) > 5 * 60) {
            throw new RestException("请求失败");
        }
        String signStr = "time" + time + "token" + token + reqJson.toString() + appSignKey;
        signStr = signStr.replaceAll(" ", "");
        signStr = URLEncoder.encode(signStr, "UTF-8");
        if(!sign.equals(StringUtil.toMD5(signStr))) {
            throw new RestException("校验签名失败");
        }
        if(UserUtil.tobCurrentUser() != null){
            UserUtil.tobUserExpireReset();
            TobUserDto tobUserDto = UserUtil.tobCurrentUser();
            tobUserDto.setVersion(request.getParameter("api_version"));
            tobUserDto.setOrderChannel(request.getParameter("client_channel") == null ? null : Integer.valueOf(request.getParameter("client_channel")));
            UserUtil.setTobCurrentUser(tobUserDto);
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        try{
//            if(request.getContentType() == null) {
//                return;
//            }
//            Date reqTime = (Date) request.getAttribute(interStartTimeKey);
//            TInterLog interLog = new TInterLog();
//            interLog.setReqUrl(request.getRequestURL().toString());
//            interLog.setReqTime(reqTime);
//            interLog.setRespTime(new Date());
//            interLog.setConsumeTime(interLog.getRespTime().getTime() - interLog.getReqTime().getTime());
//            interLog.setReqBody(SessionUtil.restReqBody());
//            interLog.setRespBody(SessionUtil.restRespBody());
//            interLog.setUserId(null);
//            LogUtil.addInterLog(interLog);
        }catch (Exception e){
           log.error("系统异常",e);
        }
    }

    private Boolean isOpenUrl(HttpServletRequest httpServletRequest) {
        return httpServletRequest.getServletPath().startsWith("/open") ? true : false;
    }
}